<?php
/**
 * StatZone default controller
 * 
 * @package    USS.StatZone
 * @subpackage Components
 * @link www.ugenix.co.za www.statzone.co.za
 * @license		Commercial
 * @author Salie Hendricks
 */


// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.controller' );

/**
 * @package		USS
 * @subpackage	StatZone
 */
class StatZoneControllerClub extends JController
{
	/**
	 * constructor (registers additional tasks to methods)
	 * @return void
	 */
	function __construct()
	{
		parent::__construct();

		// Register Extra tasks
		$this->registerTask( 'add'  , 	'edit' );
        $this->registerTask( 'apply',		'save' );
        $this->registerTask( 'unpublish',	'publish' );
	}

    /**
	 * Display the list of clubs
	 */
	function display()
	{
		global $mainframe;

		$db =& JFactory::getDBO();

		$context			= 'com_statzone.club.list.';
		$filter_order		= $mainframe->getUserStateFromRequest( $context.'filter_order',		'filter_order',		'content.title' ,	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $context.'filter_order_Dir',	'filter_order_Dir',	'',			'word' );
		$filter_provid		= $mainframe->getUserStateFromRequest( $context.'filter_provid',		'filter_provid',		'',			'int' );
		$filter_state		= $mainframe->getUserStateFromRequest( $context.'filter_state',		'filter_state',		'',			'word' );
		$search				= $mainframe->getUserStateFromRequest( $context.'search',			'search',			'',			'string' );

		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = $mainframe->getUserStateFromRequest( $context.'limitstart', 'limitstart', 0, 'int' );

		$where = array();

		if ( $filter_state )
		{
			if ( $filter_state == 'P' ) {
				$where[] = 'c.showClub = 1';
			}
			else if ($filter_state == 'U' ) {
				$where[] = 'c.showClub = 0';
			}
		}
		if ($filter_provid) {
			$where[] = 'c.provinceid = ' . (int) $filter_provid;
		}
		if ($search) {
			$where[] = 'LOWER(content.title) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
		}

		$where		= count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '';
		$orderby	= ' ORDER BY '. $filter_order .' '. $filter_order_Dir ; 

        //echo '$filter_order: '.$filter_order;

		// get the total number of records
		$query = 'SELECT COUNT(*)'
		. ' FROM #__statzone_clubs AS c'
		//. ' LEFT JOIN #__categories AS cc ON cc.id = b.catid'
		. $where
		;
		$db->setQuery( $query );
		$total = $db->loadResult();

		jimport('joomla.html.pagination');
		$pageNav = new JPagination( $total, $limitstart, $limit );

		$query = 'SELECT c.*, content.title AS name, provinces.name AS province_name, content.state'
		. ' FROM #__statzone_clubs AS c'
		. ' INNER JOIN #__content AS content ON c.contentid = content.id'
		. ' INNER JOIN #__statzone_province AS provinces ON c.provinceid = provinces.id'
		. $where
		. $orderby
		;
		$db->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
        
		$rows = $db->loadObjectList();
        //echo $query;
        
        // ________build list of provinces ________
        $javascript		= 'onchange="submitform();"';
        //, check in com_banner how to do this for a non generic list.
        
        $sql = 'SELECT id as provinceid, name'
		. ' FROM #__statzone_province'
		;
		$db->setQuery($sql);
		if (!$db->query())
		{
			$this->setRedirect( 'index.php?option=com_statzone' );
			return JError::raiseWarning( 500, $db->getErrorMsg() );
		}

		$provincelist[]		= JHTML::_('select.option',  '0', JText::_( '- Select Province -' ), 'provinceid', 'name' );
		$provincelist			= array_merge( $provincelist, $db->loadObjectList() );
		$lists['provinceid']		= JHTML::_('select.genericlist',   $provincelist, 'provinceid', 'class="inputbox" size="1"','provinceid', 'name', $row->provinceid);

		// state filter
		$lists['state']	= JHTML::_('grid.state',  $filter_state);
        $lists['filter_provid']	= JHTML::_('select.genericlist',   $provincelist, 'filter_provid', 'class="inputbox" size="1"'.$javascript,'provinceid', 'name', $filter_provid);
        
        
		// table ordering
		$lists['order_Dir']	= $filter_order_Dir;
		$lists['order']		= $filter_order;

		// search filter
		$lists['search']= $search;

		require_once(JPATH_COMPONENT.DS.'views'.DS.'clubs.php');
		StatZoneViewClubs::clubs( $rows, $pageNav, $lists );
	}
    
	/**
	 * display the edit form
	 * @return void
	 */
	function edit()
	{
        $db		=& JFactory::getDBO();
		$user	=& JFactory::getUser();

        if ($this->_task == 'edit') 
        {
			$cid	= JRequest::getVar('cid', array(0), 'method', 'array');
			$cid	= array((int) $cid[0]);
		} 
        else 
        {
			$cid	= array( 0 );
		}

        $lists = array();
        
		$option = JRequest::getCmd('option');

        
        
        $row =& JTable::getInstance('clubs', 'Table');
		$row->load( $cid[0] );//$cid[0]

        //get the list of provinces from the db
        $sql = 'SELECT id as provinceid, name'
		. ' FROM #__statzone_province'
		;
		$db->setQuery($sql);
		if (!$db->query())
		{
			$this->setRedirect( 'index.php?option=com_statzone' );
			return JError::raiseWarning( 500, $db->getErrorMsg() );
		}

		$provincelist[]		= JHTML::_('select.option',  '0', JText::_( 'Select Province' ), 'provinceid', 'name' );
		$provincelist			= array_merge( $provincelist, $db->loadObjectList() );
		$lists['provinceid']		= JHTML::_('select.genericlist',   $provincelist, 'provinceid', 'class="inputbox" size="1"','provinceid', 'name', $row->provinceid );

        //$lists['provid']		= JHTML::_('list.provinces',  'provid', 'com_statzone', intval( $row->id ) );
        
		$row =& JTable::getInstance('clubs', 'Table');
		$row->load( $cid[0] );


        $query = 'SELECT c.title FROM #__content AS c WHERE id = '. $row->contentid; //$this->get('contentid');
        $db->setQuery( $query );
        $name = $db->loadResult();
        
        
        require_once(JPATH_COMPONENT.DS.'views'.DS.'clubs.php');
		StatZoneViewClubs::singleClub( $row, $lists,$name );		
	}

	/**
	 * save a record (and redirect to main page)
	 * @return void
	 */
	function save()
	{
    
        // Check for request forgeries
		//JRequest::checkToken() or die( 'Invalid Token' );

		//$this->setRedirect( 'index.php?option=com_statzone' );

		// Initialize variables
		$db =& JFactory::getDBO();
        
		$post	= JRequest::get( 'post' );
		
        $row =& JTable::getInstance('clubs', 'Table');

		if (!$row->bind( $post )) {
            echo 'Unable to bind: '. $row->getError();
			//return JError::raiseWarning( 500, $row->getError() );
		}
        
        if (!$row->check()) {
            echo 'check failed';
			//return JError::raiseWarning( 500, $row->getError() );
		}
         //save the province to the club table
        if (!$row->store()) {
            echo 'Store() failed';
			//return JError::raiseWarning( 500, $row->getError() );
		}
        $row->checkin();
        
        //get the name and save it to the content id
        $clubid = $post['id'];
        $name= $post['name'];
        $articleId = $post['contentid'];
        if($clubid > 0)
        {
            $sql = 'UPDATE #__content SET title =\''. $name . '\' WHERE id = '. $articleId ;
            echo 'Heres the SQL: ' . $sql;
            $db->execute($sql);
        }
        else
        {
            //inserting a new content item for this club
            //get the section and category to add this content item 
            $sql = 'SELECT value FROM #__statzone_settings WHERE name = \'SectionID\'';
            $db->setQuery( $sql );
            $sectionID = $db->loadResult(); //section id = 5
            
            $sql = 'SELECT value FROM #__statzone_settings WHERE name = \'ClubCategoryID\'';
            $db->setQuery( $sql );
            $clubCategoryID = $db->loadResult(); //category id clubs = 35 (players = 34, matches = 36)
            
            $sql = 'INSERT INTO `#__content` values(\'-1\',\''. $name . '\',\''. $name . '\',\'\',\'Club info not available \',\'\', \'1\', \''. $sectionID .'\', \'0\', \''. $clubCategoryID .'\', NOW(), \'1\', \'\', \'0000-00-00 00:00:00\', \'1\', \'0\', \'0000-00-00 00:00:00\', CURDATE(), \'0000-00-00 00:00:00\', '
                    .' \'\', \'\', \'pageclass_sfx=\nback_button=\nitem_title=1\nlink_titles=\nintrotext=1\nsection=0\nsection_link=0\ncategory=0\ncategory_link=0\nrating=\nauthor=\ncreatedate=\nmodifydate=\npdf=\nprint=\nemail=\nkeyref=\ndocbook_type=\', \'1\', \'0\', \'1\', \'Clubs, Statzone\', \''.$name.'\', \'0\', \'0\',\'Statzone Clubs\');';
                    
                    
            //echo 'section id = '. $sectionID .' clubcategoryid = '.$clubCategoryID ;         
            //echo 'Heres the SQL: ' . $sql;
            $db->setQuery($sql);
            if (!$db->query())
            {
                JError::raiseError( 500, $db->stderr() );
                return false;
            }
            $insertedContentId = $db->insertid();
            
            $sql =' UPDATE `#__statzone_clubs` SET contentid = '. $insertedContentId .' WHERE id = '. $row->id . ';';
            $db->setQuery($sql);
            if (!$db->query())
            {
                JError::raiseError( 500, $db->stderr() );
                return false;
            }
            
        }
                
        switch ($task)
		{
			case 'apply':
				$link = 'index.php?option=com_statzone&task=edit&cid[]='. $row->id ;
				break;

			case 'save':
			default:
				$link = 'index.php?option=com_statzone';
				break;
		}

		$this->setRedirect( $link, JText::_( 'Item Saved' ) );
        
	}

	/**
	 * remove record(s)
	 * @return void
	 */
	function remove()
	{
        // Check for request forgeries
		JRequest::checkToken() or die( 'Invalid Token' );

		$this->setRedirect( 'index.php?option=com_statzone' );

		// Initialize variables
		$db		=& JFactory::getDBO();
		$cid	= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$n		= count( $cid );
		JArrayHelper::toInteger( $cid );

		if ($n)
		{
            //delelte the content first
            $query = 'DELETE FROM #__content'
			. ' WHERE id IN (SELECT contentid FROM #__statzone_clubs WHERE id ='. implode( ' OR id = ', $cid ).')'
			;
			$db->setQuery( $query );
			if (!$db->query()) {
				JError::raiseWarning( 500, $row->getError() );
			}
            
            //now delete the actual club record
			$query = 'DELETE FROM #__statzone_clubs'
			. ' WHERE id = ' . implode( ' OR id = ', $cid )
			;
			$db->setQuery( $query );
			if (!$db->query()) {
				JError::raiseWarning( 500, $row->getError() );
			}
		}

		$this->setMessage( JText::sprintf( 'Items removed', $n ) );
	}

    function publish()
	{
		// Check for request forgeries
		JRequest::checkToken() or die( 'Invalid Token' );

		$this->setRedirect( 'index.php?option=com_statzone' );

        // Initialize variables
		$db			=& JFactory::getDBO();
		$user		=& JFactory::getUser();
		$cid		= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$task		= JRequest::getCmd( 'task' );
		$publish	= ($task == 'publish');
		$n			= count( $cid );

		if (empty( $cid )) {
			return JError::raiseWarning( 500, JText::_( 'No items selected' ) );
		}

		JArrayHelper::toInteger( $cid );
		$cids = implode( ',', $cid );

		$query = 'UPDATE #__statzone_clubs'
		. ' SET showClub = ' . (int) $publish
		. ' WHERE id IN ( '. $cids.'  )'
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			return JError::raiseWarning( 500, $row->getError() );
		}
        
        $query = 'UPDATE #__content'
		. ' SET state = ' . (int) $publish
		. ' WHERE id IN ( SELECT contentid FROM #__statzone_clubs WHERE id IN ('. $cids .'))'
		;
        $db->setQuery( $query );
		if (!$db->query()) {
			return JError::raiseWarning( 500, $row->getError() );
		}
        
		$this->setMessage( JText::sprintf( $publish ? 'Items published' : 'Items unpublished', $n ) );
	}
    
	/**
	 * cancel editing a record
	 * @return void
	 */
	function cancel()
	{
		$msg = JText::_( 'Operation Cancelled' );
		$this->setRedirect( 'index.php?option=com_statzone', $msg );
	}
}
?>
